﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Kingdee.BOS.WebApi.FormService;
using LanDBom.Models;
using MathNet.Numerics.Distributions;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using static NPOI.HSSF.Record.UnicodeString;

namespace LanDBom.Controllers
{
    public class paricesController : Controller
    {
        private LDbaseEntities db = new LDbaseEntities();

        // GET: parices
        public ActionResult Index(string pp = "", string ming = "", string shi = "", string shund = "", string Zhisnd = "", int state = 0)
        {
            var parice = db.parice.Include(p => p.mateial).ToList();
            foreach (parice parices in parice)
            {
                if (parices.PA_Pinpai == null)
                {
                    parices.PA_Pinpai = "";
                }
                if (parices.PA_Shuxing == null)
                {
                    parices.PA_Shuxing = 0;
                }
                if (parices.PA_Time == null)
                {
                    parices.PA_Time = "";
                }
            }
            if (pp != "")
            {
                parice = parice.Where(s => s.PA_Pinpai.Contains(pp)).ToList();
            }
            if (ming != "")
            {
                parice = parice.Where(s => s.PA_Shuxing == int.Parse(ming)).ToList();
            }
            if (Zhisnd != "")
            {
                parice = parice.Where(s => s.PA_ZhongL.Contains(Zhisnd)).ToList();
            }
            if (shi != "")
            {
                parice = parice.Where(s => s.PA_KZ == shi).ToList();
            }
            var fenlei = db.mateial.ToList();
            ViewBag.fenlei = fenlei;
            var Jins = shund == "" ? 0 : int.Parse(shund);
            var tes = parice.Count();//行数
            var yeshu = tes / 30;//页数
            ViewBag.Yeshu = tes;
            ViewBag.Shund = yeshu;
            parice = parice.Skip(Jins * 30).Take(30).ToList();
            //查找分类
            if (state == 1)
            {
                var list = from p in parice
                           join a in fenlei on p.PA_Shuxing equals a.MA_ID into c
                           from KI in c.DefaultIfEmpty()
                           select new { p.PA_ID, p.PA_Pinpai, p.PA_ZhongL, p.PA_KZ, p.PA_T, p.PA_Time, p.PA_LengBie, MA_fne = KI == null ? "" : KI.MA_fne };
                JsonSerializerSettings settings = new JsonSerializerSettings()
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                    Formatting = Formatting.Indented
                };
                string jsongStr = JsonConvert.SerializeObject(list, settings);
                return Content(jsongStr, "application/json");
            }
            return View(parice);
        }
        // GET: parices/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            parice parice = db.parice.Find(id);
            if (parice == null)
            {
                return HttpNotFound();
            }
            return View(parice);
        }

        // GET: parices/Create
        public ActionResult Create()
        {
            ViewBag.PA_Shuxing = new SelectList(db.mateial.Where(s => s.MA_fne != "彩印"), "MA_ID", "MA_fne");
            ViewBag.HUNF = db.parice.Distinct().ToList();
            return View();
        }

        // POST: parices/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性；有关
        // 更多详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "PA_ID,PA_Pinpai,PA_ZhongL,PA_KZ,PA_T,PA_Time,PA_LengBie,PA_Shuxing")] parice parice)
        {
            if (ModelState.IsValid)
            {
                db.parice.Add(parice);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.PA_Shuxing = new SelectList(db.mateial.Where(s => s.MA_fne != "彩印"), "MA_ID", "MA_fne", parice.PA_Shuxing);
            return View(parice);
        }

        // GET: parices/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            parice parice = db.parice.Find(id);
            if (parice == null)
            {
                return HttpNotFound();
            }
            ViewBag.PA_Shuxing = new SelectList(db.mateial, "MA_ID", "MA_fne", parice.PA_Shuxing);
            return View(parice);
        }

        // POST: parices/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性；有关
        // 更多详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "PA_ID,PA_Pinpai,PA_ZhongL,PA_KZ,PA_T,PA_Time,PA_LengBie,PA_Shuxing")] parice parice)
        {
            if (ModelState.IsValid)
            {
                db.Entry(parice).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.PA_Shuxing = new SelectList(db.mateial, "MA_ID", "MA_fne", parice.PA_Shuxing);
            return View(parice);
        }

        // GET: parices/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            parice parice = db.parice.Find(id);
            if (parice == null)
            {
                return HttpNotFound();
            }
            return View(parice);
        }

        // POST: parices/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            parice parice = db.parice.Find(id);
            db.parice.Remove(parice);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        public ActionResult changegy(int paid)
        {
            LDbaseEntities db = new LDbaseEntities();

            string jia = db.parice.Where(x => x.PA_ID == paid).First().PA_T.ToString();

            List<CraftMaterials> craftMaterials = db.CraftMaterials.Where(x => x.cl_id == paid).ToList();
            foreach (var x in craftMaterials)
            {
                string num = (int.Parse(x.prrw_guige) * int.Parse(jia)).ToString();

                CraftMaterials craftMaterials1 = db.CraftMaterials.Where(s => s.prrw_id == x.prrw_id).First();
                craftMaterials1.prrw_jia = num;
                db.SaveChanges();
            }

            return View();
        }
        #region 批量添加供应商
        public ActionResult Gonpl(HttpPostedFileBase file)
        {

            var path = "";
            if (path == "")
            {
                try
                {
                    //解决方案 先保存到服务器后使用
                    if (file != null && file.ContentLength > 0)
                    {
                        // 指定保存文件的路径（服务器上的实际路径）  
                        path = Server.MapPath("~/Files/");
                        // 确保目录存在  
                        Directory.CreateDirectory(path);

                        // 生成唯一的文件名（这里只是简单示例，你可能需要更复杂的唯一性逻辑）  
                        string fileName = file.FileName;//只保存一个文件 有文件就删除

                        // 保存文件到服务器  
                        string filePath = Path.Combine(path, fileName);
                        file.SaveAs(filePath);//真实路径
                        System.Data.DataTable table = MaterialController.ExcelToDatatables(filePath, "Sheet1", true);//从第二行开始
                                                                                                                     //去除空值  直接保存
                        int sjinag = 0;
                        for (int i = 0; i < table.Rows.Count; i++)
                        {
                            DataRow dataRow = table.Rows[i];
                            var bian = dataRow[0].ToString();
                            var cuzn = db.Providers.FirstOrDefault(s => s.PR_bian == bian);
                            if (cuzn == null)
                            {
                                var clis = new Providers();
                                clis.PR_bian = bian.ToString();
                                clis.PR_name = dataRow[1].ToString();
                                clis.PR_Lei1 = dataRow[2].ToString();
                                clis.PR_Lei2 = dataRow[3].ToString();
                                clis.PR_bei = "准入";
                                db.Providers.Add(clis);
                            }
                            else
                            {
                                cuzn.PR_bian = bian.ToString();
                                cuzn.PR_name = dataRow[1].ToString();
                                cuzn.PR_Lei1 = dataRow[2].ToString();
                                cuzn.PR_Lei2 = dataRow[3].ToString();
                                cuzn.PR_bei = "准入";
                                db.Entry(cuzn).State = EntityState.Modified;
                            }
                            sjinag += db.SaveChanges();
                        }
                        string message = sjinag == table.Rows.Count ? "添加成功" : "添加失败";
                        return Content(message);
                    }
                    else
                    {
                        // 返回失败消息  
                        return Json(new { success = false, message = "没有文件被上传或者文件大小为0." });
                    }
                }
                catch (DbEntityValidationException)
                {

                    return Json(new { Success = false, Message = "系统错误！" });
                }
            }
            return View();
        }
        #endregion
    }
}
